#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@file_name: cancel_task.py
@date: 2025-07-26 17:18
@author: Falling Snow
@desc: 取消任务
"""

import asyncio
from asyncio import CancelledError

from util import delay


async def main():
    long_task = asyncio.create_task(delay(10))

    seconds_elapsed = 0

    while not long_task.done():
        print("long_task 任务没有完成, 在一秒后进行检测")
        await asyncio.sleep(1)
        seconds_elapsed += 1
        if seconds_elapsed == 5:
            long_task.cancel()

    try:
        # 调用cancel时候会触发 异常, 然后我们进行捕获
        await long_task
    except CancelledError:
        print('long_task 任务被取消了!')


if __name__ == '__main__':
    asyncio.run(main())
